package org.jeecg.qis.controller;

import com.baomidou.dynamic.datasource.annotation.DS;
import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.baomidou.mybatisplus.core.metadata.IPage;
import com.baomidou.mybatisplus.extension.plugins.pagination.Page;
import org.jeecg.qis.entity.QisProcdetailCfg;
import org.jeecg.qis.entity.QisProcheadCfg;
import org.jeecg.qis.service.IQisProcdetailCfgService;
import org.jeecg.qis.service.IQisProcheadCfgService;
import io.swagger.annotations.Api;
import io.swagger.annotations.ApiOperation;
import lombok.extern.slf4j.Slf4j;
import org.apache.shiro.SecurityUtils;
import org.jeecg.common.api.CommonAPI;
import org.jeecg.common.api.vo.Result;
import org.jeecg.common.aspect.annotation.AutoLog;
import org.jeecg.common.system.base.controller.JeecgController;
import org.jeecg.common.system.query.QueryGenerator;
import org.jeecg.common.system.vo.LoginUser;
import org.jeecg.common.util.CudUtils;
import org.jeecg.common.util.oConvertUtils;
import org.jeecgframework.poi.excel.ExcelImportUtil;
import org.jeecgframework.poi.excel.def.NormalExcelConstants;
import org.jeecgframework.poi.excel.entity.ExportParams;
import org.jeecgframework.poi.excel.entity.ImportParams;
import org.jeecgframework.poi.excel.view.JeecgEntityExcelView;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.*;
import org.springframework.web.multipart.MultipartFile;
import org.springframework.web.multipart.MultipartHttpServletRequest;
import org.springframework.web.servlet.ModelAndView;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.io.IOException;
import java.text.SimpleDateFormat;
import java.util.*;
import java.util.stream.Collectors;

/**
 * @Description: 过程检验配置主表
 * @Author: shaolong
 * @Date: 2022-10-10
 * @Version: V1.0
 */
@Api(tags = "过程检验配置主表")
@RestController
@RequestMapping("/qis/qisProcheadCfg")
@Slf4j
public class QisProcheadCfgController extends JeecgController<QisProcheadCfg, IQisProcheadCfgService> {

	@Autowired
	private IQisProcheadCfgService qisProcheadCfgService;

	@Autowired
	private IQisProcdetailCfgService qisProcdetailCfgService;

	@Autowired
	private CommonAPI commonAPI;


	/*---------------------------------主表处理-begin-------------------------------------*/

	/**
	 * 分页列表查询  erp
	 *
	 * @param qisProcheadCfg
	 * @param pageNo
	 * @param pageSize
	 * @param req
	 * @return
	 */
	//@AutoLog(value = "过程检验配置主表-分页列表查询")
	@ApiOperation(value = "过程检验配置主表-分页列表查询", notes = "过程检验配置主表-分页列表查询")
	@GetMapping(value = "/list")
	@DS("#header.his")
	public Result<IPage<QisProcheadCfg>> queryPageList(QisProcheadCfg qisProcheadCfg,
													   @RequestParam(name = "pageNo", defaultValue = "1") Integer pageNo,
													   @RequestParam(name = "pageSize", defaultValue = "10") Integer pageSize,
													   HttpServletRequest req) {
		QueryWrapper<QisProcheadCfg> queryWrapper = QueryGenerator.initQueryWrapper(qisProcheadCfg, req.getParameterMap());
		Page<QisProcheadCfg> page = new Page<QisProcheadCfg>(pageNo, pageSize);
		IPage<QisProcheadCfg> pageList = qisProcheadCfgService.page(page, queryWrapper);
		return Result.OK(pageList);
	}

	/**
	 * 添加
	 *
	 * @param qisProcheadCfg
	 * @return
	 */
	@AutoLog(value = "过程检验配置主表-添加")
	@ApiOperation(value = "过程检验配置主表-添加", notes = "过程检验配置主表-添加")
	@PostMapping(value = "/add")
	@DS("#header.line")
	public Result<String> add(@RequestBody QisProcheadCfg qisProcheadCfg) throws Exception {
		Integer value = commonAPI.getCounterValue("recId.qis_prochead_cfg","0");
		qisProcheadCfg.setRecId(value.toString());
		//生成检验单
		Integer checkNo = commonAPI.getCounterValue("checklist","1");

		qisProcheadCfgService.save(qisProcheadCfg);
		return Result.OK("添加成功！");
	}



	/**
	 * 编辑
	 *
	 * @param qisProcheadCfg
	 * @return
	 */
	@AutoLog(value = "过程检验配置主表-编辑")
	@ApiOperation(value = "过程检验配置主表-编辑", notes = "过程检验配置主表-编辑")
	@RequestMapping(value = "/edit", method = {RequestMethod.PUT, RequestMethod.POST})
	@DS("#header.line")
	public Result<String> edit(@RequestBody QisProcheadCfg qisProcheadCfg) {
		qisProcheadCfgService.edit(qisProcheadCfg);
		return Result.OK("编辑成功!");
	}

	/**
	 * 通过id删除
	 *
	 * @param map
	 * @return
	 */
	@AutoLog(value = "过程检验配置主表-通过id删除")
	@ApiOperation(value = "过程检验配置主表-通过id删除", notes = "过程检验配置主表-通过id删除")
	@RequestMapping(value = "/delete")
	@DS("#header.line")
	public Result<String> delete(@RequestBody QisProcheadCfg qisProcheadCfg) {
		qisProcheadCfgService.delMain(qisProcheadCfg.getRecId());
		return Result.OK("删除成功!");
	}

	/**
	 * 批量删除
	 *
	 * @param ids
	 * @return
	 */
	@AutoLog(value = "过程检验配置主表-批量删除")
	@ApiOperation(value = "过程检验配置主表-批量删除", notes = "过程检验配置主表-批量删除")
	@DeleteMapping(value = "/deleteBatch")
	@DS("#header.line")
	public Result<String> deleteBatch(@RequestParam(name = "ids", required = true) String ids) {
		this.qisProcheadCfgService.delBatchMain(Arrays.asList(ids.split(",")));
		return Result.OK("批量删除成功!");
	}

	/**
	 * 导出
	 *
	 * @return
	 */
	@RequestMapping(value = "/exportXls")
	@DS("#header.his")
	public ModelAndView exportXls(HttpServletRequest request, QisProcheadCfg qisProcheadCfg) {
		return super.exportXls(request, qisProcheadCfg, QisProcheadCfg.class, "过程检验配置主表");
	}

	/**
	 * 导入
	 *
	 * @return
	 */
	@RequestMapping(value = "/importExcel", method = RequestMethod.POST)
	@DS("#header.line")
	public Result<?> importExcel(HttpServletRequest request, HttpServletResponse response) {
		return super.importExcel(request, response, QisProcheadCfg.class);
	}
	/*---------------------------------主表处理-end-------------------------------------*/


	/*--------------------------------子表处理-过程检验配置明细表-begin----------------------------------------------*/

	/**
	 * 通过主表ID查询1
	 *
	 * @return
	 */
	//@AutoLog(value = "过程检验配置明细表-通过主表ID查询")
	@ApiOperation(value = "过程检验配置明细表-通过主表ID查询", notes = "过程检验配置明细表-通过主表ID查询")
	@GetMapping(value = "/listQisProcdetailCfgByMainId")
	@DS("#header.his")
	public Result<IPage<QisProcdetailCfg>> listQisProcdetailCfgByMainId(QisProcdetailCfg qisProcdetailCfg,
																		@RequestParam(name = "pageNo", defaultValue = "1") Integer pageNo,
																		@RequestParam(name = "pageSize", defaultValue = "10") Integer pageSize,
																		HttpServletRequest req) {
		//QueryWrapper<QisProcdetailCfg> queryWrapper = QueryGenerator.initQueryWrapper(qisProcdetailCfg, req.getParameterMap());
		Page<QisProcdetailCfg> page = new Page<QisProcdetailCfg>(pageNo, pageSize);
		IPage<QisProcdetailCfg> pageList = qisProcdetailCfgService.pageList(page, qisProcdetailCfg);
		return Result.OK(pageList);
	}

	/**
	 * 添加
	 *
	 * @param qisProcdetailCfg
	 * @return
	 */
	@AutoLog(value = "过程检验配置明细表-添加")
	@ApiOperation(value = "过程检验配置明细表-添加", notes = "过程检验配置明细表-添加")
	@PostMapping(value = "/addQisProcdetailCfg")
	@DS("#header.line")
	public Result<String> addQisProcdetailCfg(@RequestBody QisProcdetailCfg qisProcdetailCfg) throws Exception {
		Integer counterValue = commonAPI.getCounterValue("recId_qis_procdetail_cfg","0");
		qisProcdetailCfg.setRecId(counterValue);
		qisProcdetailCfgService.save(qisProcdetailCfg);
		return Result.OK("添加成功！");
	}

	/**
	 * 编辑
	 *
	 * @param qisProcdetailCfg
	 * @return
	 */
	@AutoLog(value = "过程检验配置明细表-编辑")
	@ApiOperation(value = "过程检验配置明细表-编辑", notes = "过程检验配置明细表-编辑")
	@RequestMapping(value = "/editQisProcdetailCfg", method = {RequestMethod.PUT, RequestMethod.POST})
	@DS("#header.line")
	public Result<String> editQisProcdetailCfg(@RequestBody QisProcdetailCfg qisProcdetailCfg) {
		qisProcdetailCfgService.edit(qisProcdetailCfg);
		return Result.OK("编辑成功!");
	}

	/**
	 * 通过id删除
	 *
	 * @param map
	 * @return
	 */
	@AutoLog(value = "过程检验配置明细表-通过id删除")
	@ApiOperation(value = "过程检验配置明细表-通过id删除", notes = "过程检验配置明细表-通过id删除")
	@RequestMapping(value = "/deleteQisProcdetailCfg")
	@DS("#header.line")
	public Result<String> deleteQisProcdetailCfg(@RequestBody QisProcdetailCfg qisProcdetailCfg) {
		//自定义查询条件，下面的值全部满足才能删除成功
		qisProcdetailCfgService.removeById(qisProcdetailCfg.getRecId());
		return Result.OK("删除成功!");
	}

	/**
	 * 批量删除
	 *
	 * @param list
	 * @return
	 */
	@AutoLog(value = "过程检验配置明细表-批量删除")
	@ApiOperation(value = "过程检验配置明细表-批量删除", notes = "过程检验配置明细表-批量删除")
	@RequestMapping(value = "/deleteBatchQisProcdetailCfg")
	@DS("#header.line")
	public Result<String> deleteBatchQisProcdetailCfg(@RequestBody List<QisProcdetailCfg> list) {
		list.forEach(item->{
			this.qisProcdetailCfgService.removeById(item);
		});
		return Result.OK("批量删除成功!");
	}

	/**
	 * 导出
	 *
	 * @return
	 */
	@RequestMapping(value = "/exportQisProcdetailCfg")
	@DS("#header.his")
	public ModelAndView exportQisProcdetailCfg(HttpServletRequest request, QisProcdetailCfg qisProcdetailCfg) {
		// Step.1 组装查询条件
		QueryWrapper<QisProcdetailCfg> queryWrapper = QueryGenerator.initQueryWrapper(qisProcdetailCfg, request.getParameterMap());
		LoginUser sysUser = (LoginUser) SecurityUtils.getSubject().getPrincipal();

		// Step.2 获取导出数据
		List<QisProcdetailCfg> pageList = qisProcdetailCfgService.list(queryWrapper);
		List<QisProcdetailCfg> exportList = null;

		// 过滤选中数据
		String selections = request.getParameter("selections");
		if (oConvertUtils.isNotEmpty(selections)) {
			List<String> selectionList = Arrays.asList(selections.split(","));
			exportList = pageList.stream().filter(item -> selectionList.contains(item.getRecId())).collect(Collectors.toList());
		} else {
			exportList = pageList;
		}

		// Step.3 AutoPoi 导出Excel
		ModelAndView mv = new ModelAndView(new JeecgEntityExcelView());
		//此处设置的filename无效,前端会重更新设置一下
		mv.addObject(NormalExcelConstants.FILE_NAME, "过程检验配置明细表");
		mv.addObject(NormalExcelConstants.CLASS, QisProcdetailCfg.class);
		mv.addObject(NormalExcelConstants.PARAMS, new ExportParams("过程检验配置明细表报表", "导出人:" + sysUser.getRealname(), "过程检验配置明细表"));
		mv.addObject(NormalExcelConstants.DATA_LIST, exportList);
		return mv;
	}

	/**
	 * 导入
	 *
	 * @return
	 */
	@RequestMapping(value = "/importQisProcdetailCfg/{mainId}")
	@DS("#header.line")
	public Result<?> importQisProcdetailCfg(HttpServletRequest request, HttpServletResponse response, @PathVariable("mainId") String mainId) {
		MultipartHttpServletRequest multipartRequest = (MultipartHttpServletRequest) request;
		Map<String, MultipartFile> fileMap = multipartRequest.getFileMap();
		for (Map.Entry<String, MultipartFile> entity : fileMap.entrySet()) {
			// 获取上传文件对象
			MultipartFile file = entity.getValue();
			ImportParams params = new ImportParams();
			params.setTitleRows(2);
			params.setHeadRows(1);
			params.setNeedSave(true);
			try {
				long start = System.currentTimeMillis();
				List<QisProcdetailCfg> list = ExcelImportUtil.importExcel(file.getInputStream(), QisProcdetailCfg.class, params);
				for (QisProcdetailCfg temp : list) {
					Integer counterValue = commonAPI.getCounterValue("recId_qis_procdetail_cfg","0");
					temp.setRecId(counterValue);
					temp.setHeadid(mainId);
					qisProcdetailCfgService.save(temp);
				}
				log.info("消耗时间" + (System.currentTimeMillis() - start) + "毫秒");
				return Result.OK("文件导入成功！数据行数：" + list.size());
			} catch (Exception e) {
				log.error(e.getMessage(), e);
				return Result.error("文件导入失败:" + e.getMessage());
			} finally {
				try {
					file.getInputStream().close();
				} catch (IOException e) {
					e.printStackTrace();
				}
			}
		}
		return Result.error("文件导入失败！");
	}

	/*--------------------------------子表处理-过程检验配置明细表-end----------------------------------------------*/


}
